package be.bejug.scrumadmin.spring;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;

/**
 * Base application class.
 * 
 * @author Glenn Dejaeger
 * 
 */
public abstract class BaseApplication extends Application implements
		HttpServletRequestListener {

	/**
	 * Serial Version UID.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(BaseApplication.class);

	/**
	 * Gets the locale.
	 * 
	 * @return the {@link Locale}
	 */
	@Override
	public Locale getLocale() {
		return LocaleContextHolder.getLocale();
	}

	/**
	 * Sets the locale.
	 * 
	 * @param locale
	 *            the {@link Locale}
	 */
	@Override
	public void setLocale(final Locale locale) {
		LocaleContextHolder.setLocale(locale);
	}

	/**
	 * Executed when request starts.
	 * 
	 * @param request
	 *            the {@link HttpServletRequest}
	 * @param response
	 *            the {@link HttpServletResponse}
	 */
	public final void onRequestStart(final HttpServletRequest request,
			final HttpServletResponse response) {
		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("onRequestStart()");
		}
		ApplicationHolder.setApplication(this);
		requestStart(request, response);
	}

	/**
	 * Executed when request ends.
	 */
	public final void onRequestEnd(final HttpServletRequest request,
			final HttpServletResponse response) {
		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("onRequestEnd()");
		}
		try {
			requestEnd(request, response);
		} finally {
			ApplicationHolder.resetApplication();
		}
	}

	/**
	 * Request end method.
	 * 
	 * @param request
	 *            the {@link HttpServletRequest}
	 * @param response
	 *            the {@link HttpServletResponse}
	 */
	public void requestEnd(final HttpServletRequest request,
			final HttpServletResponse response) {
		LOGGER.info("End of request");
	}

	/**
	 * Request start method.
	 * 
	 * @param request
	 *            the {@link HttpServletRequest}
	 * @param response
	 *            the {@link HttpServletResponse}
	 */
	public void requestStart(final HttpServletRequest request,
			final HttpServletResponse response) {
		LOGGER.info("Start of request");
	}

}
